<template>
  <!-- 外部用户 -->
  <div class="info" v-show="switchName === 'EXTERNAL'">
    <!-- <p class="logo-box"></p> -->
    <div class="logo-wrap">
      <img :src="logoImg" class="logoImg" />
      <!-- <h2 style="text-align: center; color: #84aaff">{{ settings.title }}</h2> -->
    </div>
    <el-row class="hander">
      <el-col :span="11" class="hander-item" @click="model.loginType = 'mobile'"
        ><span :class="model.loginType === 'mobile' ? 'isActive' : ''"
          >手机号登录</span
        ></el-col
      >
      <el-col :span="2" class="hander-center">|</el-col>
      <el-col
        :span="11"
        class="hander-item"
        @click="model.loginType = 'username'"
        ><span :class="model.loginType === 'username' ? 'isActive' : ''"
          >用户名登录</span
        ></el-col
      >
    </el-row>
    <div
      v-if="model.loginType === 'mobile'"
      class="ldap-wrap"
      :class="model.loginType === 'mobile' ? 'animationTele' : ''"
    >
      <el-form
        :model="model"
        :rules="rulesRules"
        ref="ruleForm"
        @keyup.enter="onBehavior"
      >
        <el-form-item prop="telephone">
          <el-input
            clearable
            size="medium"
            v-model.trim="model.telephone"
            placeholder="请输入手机号"
            class="no-border"
            maxlength="64"
            autofocus
            prefix-icon="el-icon-phone"
          >
          </el-input>
        </el-form-item>
        <el-form-item class="custom-item" prop="textCode">
          <el-input
            clearable
            size="medium"
            v-model.trim="model.textCode"
            placeholder="请输入验证码"
            style="width: 235px; display: inline-block; vertical-align: bottom"
            maxlength="64"
          >
            ></el-input
          >
          <el-button id="codeButton" @click.prevent="getTextCode"
            >获取验证码</el-button
          >
        </el-form-item>
        <br />
        <el-form-item>
          <el-button
            class="custom-item--btn"
            size="medium"
            type="primary"
            @click.prevent="onBehavior"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div
      v-if="model.loginType === 'username'"
      :class="model.loginType === 'username' ? 'animation' : ''"
    >
      <el-form
        :model="model"
        :rules="rulesRules"
        ref="ruleForm"
        @keyup.enter="onBehavior"
      >
        <el-form-item prop="userName">
          <el-input
            clearable
            size="medium"
            v-model.trim="model.userName"
            placeholder="请输入用户名"
            class="no-border"
            maxlength="64"
            autofocus
            prefix-icon="el-icon-user"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="passWord">
          <el-input
            clearable
            size="medium"
            type="password"
            show-password
            v-model.trim="model.passWord"
            placeholder="请输入密码"
            class="no-border"
            maxlength="64"
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>
        <el-form-item class="custom-item" prop="identify">
          <el-input
            clearable
            size="medium"
            v-model.trim="model.identify"
            placeholder="验证码"
            style="width: 235px; display: inline-block; vertical-align: middle"
            maxlength="64"
          ></el-input>
          <Identify
            class="identify-box"
            :contentWidth="94"
            :contentHeight="36"
            backgroundColor="#08132A"
            :drawLine="true"
            :drawDot="false"
            :identifyCode="activeData.identifyCode"
            @click="refreshCode"
          ></Identify>
        </el-form-item>
        <br />
        <el-form-item>
          <el-button
            class="custom-item--btn"
            size="medium"
            type="primary"
            @click.prevent="onBehavior"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>

  <!--LDAP内部用户-->
  <div class="info" v-if="switchName === 'INTERNAL'">
    <div class="logo-wrap">
      <img :src="logoImg" class="logoImg" />
    </div>

    <div :class="'animation'">
      <el-row class="hander1">
        <el-col :span="11" class="hander1-item">
          <span>内部用户</span>
        </el-col>
      </el-row>
      <el-form
        :model="model"
        :rules="rulesRules"
        ref="ruleForm"
        @keyup.enter="handleToLdap"
      >
        <br />
        <el-form-item>
          <el-button
            class="custom-item--btn"
            size="medium"
            type="primary"
            @click.prevent="handleToLdap"
            >LDAP登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>

  <div
    class="switchButton"
    v-show="switchName === 'EXTERNAL'"
    @click="switchName = 'INTERNAL'"
  >
    <p>内部用户</p>
  </div>

  <div
    class="switchButton"
    v-show="switchName === 'INTERNAL'"
    @click="switchName = 'EXTERNAL'"
  >
    <p>外部用户</p>
  </div>
</template>

<script lang="ts">
import settings from "/@/settings";
import logoImg from "/@/assets/logo.png";

import {
  ref,
  defineComponent,
  PropType,
  onBeforeMount,
  onMounted,
  getCurrentInstance,
  // watch,
  // nextTick,
  toRef
} from "vue";
import { storageSession } from "/@/utils/storage";
import Identify from "/@/components/Identify/index.vue";
import { clickEvent } from "/@/utils/func";
import { mobileLogin } from "/@/api/log";
import NotifMessage from "/@/utils/message/notification";
export interface ContextProps {
  userName: string;
  passWord: string;
  telephone?: number;
  textCode?: number;
  dynamicText?: string;
  identify: string;
  loginType: string;
}

import { useRouter } from "vue-router";
import { string } from "vue-types";

// import { initRouter } from "/@/router";

export default defineComponent({
  name: "Info",
  props: {
    ruleForm: {
      type: Object as PropType<ContextProps>,
      require: true
    }
  },
  emits: ["onBehavior"],
  components: { Identify },
  setup(props, ctx) {
    let vm: any;
    // let activeName = ref("mobile");
    let switchName = ref("EXTERNAL");
    const activeData = ref({
      identifyCodes: "1234567890abcdef",
      identifyCode: "", //用户输入的验证码
      textCode: "", //用户输入短信验证码
      phone: "",
      contentCode: "", //随机产生的验证码
      timer: null,
      showLoginCode: true, //倒计时
      count: null, //倒计时时间

      checked: false
    });

    const model = toRef(props, "ruleForm");
    model.value.loginType = "mobile";
    let tips = ref("注册");
    // let tipsFalse = ref("登录");

    // const route = useRoute();
    const router = useRouter();

    // watch(
    //   route,
    //   async ({ path }): Promise<void> => {
    //     await nextTick();
    //     path.includes("register")
    //       ? (tips.value = "登录") && (tipsFalse.value = "注册")
    //       : (tips.value = "注册") && (tipsFalse.value = "登录");
    //   },
    //   { immediate: true }
    // );

    const identifyFunc = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入验证码"));
      } else {
        if (value !== activeData.value.identifyCode) {
          callback(new Error("请输入正确的验证码"));
        }
        callback();
      }
    };

    //检查手机号是否符合格式
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^1[3-9]\d{9}$/;
      if (regMobile.test(value) == true) {
        const message = "短信验证码发送成功";
        NotifMessage.success(message);
        return callback();
      } else {
        callback(new Error("该手机号不符合格式，请输入合法的手机号"));
      }
    };

    //检验用户输入的验证码是否和发送的验证码相同
    // const checkPhoneCode = (rule, value, callback) => {
    //   if (value == activeData.value.textCode) {
    //     return callback();
    //   } else {
    //     callback(new Error("验证码输入错误"))
    //   }
    // };

    //获取手机验证码
    const getTextCode = async () => {
      //用户未输入手机号时，结束执行
      if (!model.value.telephone) {
        return;
      }
      //获取随机数(6位)
      // var numCode = "";
      // for (var i = 0; i < 6; i++) {
      //   numCode += Math.floor(Math.random()*10);
      // }
      // 储存发送的验证码，用于验证输入的手机验证码是否和本地储存相同
      // activeData.value.contentCode = numCode;
      // 向手机号发送验证码传入的参数
      // let phoneCode = {
      //   phoneNum: activeData.value.phone,
      //   contextContent: "您正在修改密码，验证码为:" + numCode + ",切勿将验证码泄露给他人。"
      // };

      //调用接口，向手机号发送验证码
      try {
        const { data } = await mobileLogin({ phone: model.value.telephone });
        if (data.status != 200) {
          // return this.$message.error("验证码发送失败！");
          return;
        } else {
          //验证码发送成功，开启60秒倒计时
          const TIME_COUNT = 60;
          if (!activeData.value.timer) {
            activeData.value.showLoginCode = false;
            activeData.value.count = TIME_COUNT;
            activeData.value.timer = setInterval(() => {
              if (
                activeData.value.count > 0 &&
                activeData.value.count <= TIME_COUNT
              ) {
                activeData.value.count -= 1;
              } else {
                activeData.value.showLoginCode = true;
                clearInterval(activeData.value.timer);
                activeData.value.timer = null;
              }
            }, 1000);
          }
        }
      } catch (err) {
        console.log(err);
      }
    };

    const rulesRules = {
      telephone: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        { validator: checkMobile, trigger: "blur" }
      ],
      textCode: [
        { required: true, message: "短信验证码不能为空", trigger: "blur" }
        //  { validator: checkPhoneCode, trigger: "blur"}
      ],
      userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      passWord: [{ required: true, message: "请输入密码", trigger: "blur" }],
      // { min: 6, message: "密码长度必须不小于6位", trigger: "blur" }
      identify: [{ validator: identifyFunc, trigger: "blur" }]
    };

    // 点击登录或注册
    const onBehavior = (evt: Object) => {
      vm.refs.ruleForm.validate((valid: boolean) => {
        if (valid) {
          ctx.emit("onBehavior", evt);
        } else {
          return false;
        }
      });
    };

    // 表单重置
    const resetForm = (): void => {
      vm.refs.ruleForm.resetFields();
      refreshCode();
    };

    // 登录、注册页面切换
    const changPage = (): void => {
      tips.value === "注册" ? router.push("/register") : router.push("/login");
    };

    const noSecret = (): void => {
      storageSession.setItem("username", "admin");
      storageSession.setItem("accessToken", "eyJhbGciOiJIUzUxMiJ9.test");
      // initRouter().then(() => {});
      router.push("/");
    };

    const toRegister = () => {
      router.push("/register");
    };

    onBeforeMount(() => {
      vm = getCurrentInstance(); //获取组件实例
    });

    onMounted(() => {
      makeCode(4);
    });

    // 验证码处理
    const randomNum = (min, max) => {
      return Math.floor(Math.random() * (max - min) + min);
    };

    // 刷新验证码
    const refreshCode = () => {
      model.value.identify = "";
      activeData.value.identifyCode = "";
      makeCode(4);
    };

    const makeCode = l => {
      for (let i = 0; i < l; i++) {
        activeData.value.identifyCode +=
          activeData.value.identifyCodes[
            randomNum(0, activeData.value.identifyCodes.length)
          ];
      }
      // console.log(activeData.value.identifyCode);
    };

    const handleToLdap = () => {
      const { origin } = window.location;
      let loginUrl = `https://ldap-sit.crc.com.cn/idp/authCenter/authenticate?response_type=code&state=1&redirect_uri=${origin}/welcome&client_id=epmssit`;

      // uat 环境
      if (import.meta.env.VITE_PROJECT_ENV === "uat") {
        loginUrl = `https://ldap-uat.crc.com.cn/idp/authCenter/authenticate?response_type=code&state=1&redirect_uri=${origin}/welcome&client_id=epmsuat`;
      } else if (import.meta.env.VITE_PROJECT_ENV === "pre") {
        // 生产环境
        loginUrl = `https://ldap.crc.com.cn/idp/authCenter/authenticate?response_type=code&state=1&redirect_uri=${origin}${encodeURIComponent(
          "/v2/#"
        )}/projects/manage/space&client_id=CRB_EMPSPRO`;
      }
      clickEvent("工程项目管理登录页面", "登录", "LDAP登录");
      window.open(loginUrl, "_self");
    };

    return {
      logoImg,
      settings,
      model,
      rulesRules,
      tips,
      activeData,
      // activeName,
      switchName,
      resetForm,
      onBehavior,
      getTextCode,
      changPage,
      noSecret,
      refreshCode,
      toRegister,
      handleToLdap
    };
  }
});
</script>

<style lang="scss" scoped>
.info {
  width: 500px;
  height: 480px;
  // background: url("../../assets/login.png") no-repeat center;
  // background-size: cover;
  background: #fff;
  position: absolute;
  border-radius: 8px;
  left: 53%;
  top: 50%;
  margin-left: -300px;
  margin-top: -220px;
  // display: flex;
  // justify-content: center;
  // align-items: center;
  padding: 50px 80px 66px;
  // @media screen and (max-width: 750px) {
  //   width: 88vw;
  //   right: 25px;
  //   top: 22vh;
  // }
  overflow: hidden;
  .logo-box {
    width: 290px;
    height: 26px;
    background: url("../../assets/login-logo.png") no-repeat center;
    background-size: 290px 26px;
    margin-bottom: 32px;
  }
  .secret {
    color: #409eff;
    font-size: 14px;
    &:hover {
      cursor: pointer;
    }
  }

  .hander {
    margin: 30px 0;
    &-item {
      text-align: center;
      font-size: 14px;
      font-weight: bold;
      color: #5f5f5f;
      &:hover {
        cursor: pointer;
        color: #5eaaf5;
      }
    }
    &-center {
      text-align: center;
      font-size: 14px;
      color: #5f5f5f;
    }
    .isActive {
      color: #84aaff;
    }
  }
}

.ldap-wrap {
  display: flex;
  justify-content: center;
  align-items: center;
  .ldapBtn {
    margin-top: 80px;
    width: 60%;
  }
}

.custom-item {
  display: flex;
  justify-content: flex-end;
  &--btn {
    width: 100%;
  }
}
.identify-box {
  display: inline-block;
  vertical-align: middle;
  height: 36px;
  margin-left: 8px;
  border-radius: 3px;
  overflow: hidden;
  cursor: pointer;
}

.logo-wrap {
  width: 100%;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;

  .logoImg {
    width: 322px;
    margin-right: 8px;
  }
}

// 登录页样式覆盖
:deep .el-input--medium.no-border .el-input__inner {
  padding-left: 30px !important;
  padding-right: 12px;
}

:deep .el-input {
  input {
    background: transparent;
    &:-webkit-autofill {
      box-shadow: 0 0 0 1000px #fff inset;
      -webkit-text-fill-color: #000;
    }
  }
}

:deep .el-input--medium.no-border .el-input__inner {
  border-left: none;
  border-top: none;
  border-right: none;
  border-radius: 0;
  padding-left: 0;
}
:deep .el-input el-input--medium el-input--suffix no-border {
  border-left: none;
  border-top: none;
  border-right: none;
  border-radius: 0;
  padding-left: 0;
}

.animationTele {
  position: relative;
  animation: myTele 0.5s;
}
.animation {
  position: relative;
  animation: myfirst 0.5s;
}

@keyframes myfirst {
  from {
    // left: 200px;
    //  transform: rotateY(130deg);
    transform: translateX(200px);
    opacity: 0;
  }
  to {
    // left: 0px;
    transform: translateX(0px);
    opacity: 1;
  }
}

@keyframes myTele {
  from {
    right: 200px;
    opacity: 0;
  }
  to {
    right: 0px;
    opacity: 1;
  }
}

.switchButton {
  position: absolute;
  width: 110px;
  height: 40px;
  background-color: #fff;
  border-radius: 6px;
  top: 3%;
  left: 88%;
  p {
    font-family: Arial, Helvetica, sans-serif;
    position: absolute;
    line-height: 41px;
    text-align: center;
    font-size: 15px;
    margin-left: 25px;
    color: #000;
    &:hover {
      cursor: pointer;
      color: #2b81d7;
    }
  }
}

#codeButton {
  margin-left: 8px;
}

.hander1 {
  margin: 30px 0px;
  &-item {
    text-align: center;
    font-size: 14px;
    font-weight: bold;
    color: #5f5f5f;
    margin-left: 91px;
  }
  &-center {
    text-align: center;
    font-size: 14px;
    color: #5f5f5f;
  }
}
</style>
